﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocket4Net;
using WebSocket4Net.Command;
using WebSocket4Net.Protocol;
using System.Threading;
using System.Net;
using System.Diagnostics;
using System.ComponentModel;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Configuration;
//using System.Windows.Forms;
namespace Helper
{
   public class SocketClient
    {
        public String Url = "";
        public String Host = "";
        public String Port = "";
        WebSocket _Client;
        string key = "kyers_software_framework_VietNam_123456789$%^@#$%#@$%#%#%$#@@";
        string Service = "50kWebsite";
        public String Data { get; set; }

       public SocketClient()
        {
            Host = ConfigurationManager.AppSettings.Get("Host");
            Port = ConfigurationManager.AppSettings.Get("Port");
        }

        public void Start(string username, out string state)
        {
            try
            {
                Url = "wss://" + Host + ":" + Port + "/";
                _Client = new WebSocket(Url, "basic", WebSocketVersion.None);
                _Client.AllowUnstrustedCertificate = true;
                _Client.Open();
                _Client.MessageReceived += new EventHandler<WebSocket4Net.MessageReceivedEventArgs>(socket_MessageReceived);
                _Client.DataReceived += new EventHandler<WebSocket4Net.DataReceivedEventArgs>(socket_DataReceived);
                int time = 0;
                while (_Client.State != WebSocketState.Open)
                {
                    if (_Client.State == WebSocketState.Open)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                    time++;
                    if (time == 30)
                    {
                        break;
                    }
                    Application.DoEvents();
                }
                time = 0;
                if (_Client.State == WebSocketState.Open)
                    Send("Authurization", username, key);

                while (true)
                {
                    if (Data != null)
                    {
                        if (Data == "OK")
                        {
                            state = "OK";
                            Data = null;
                            break;
                        }
                    }

                    Thread.Sleep(50);
                    time++;
                    if (time == 30)
                    {
                        Data = null;
                        state = "Failed";
                        break;
                    }
                    Application.DoEvents();
                }
            }
            catch
            {
                Data = null;
                state = "Failed";
                // throw new Exception("Failed");
            }

        }


        public void Send(string key, string user, string message)
        {
            try
            {
                _Client.Send(key + " " + Service + "|" + user + "|" + message);
            }
            catch
            {
                throw new Exception("Failed");
            }
        }

        /// <summary>
        /// Send object by json string
        /// </summary>
        /// <param name="session"></param>
        /// <param name="name"></param>
        /// <param name="_object"></param>
        public void SendJson(string key, string user, object _object)
        {
            try
            {
                _Client.Send(key + " " + Service + "|" + user + "|" + JsonConvert.SerializeObject(_object));
            }
            catch
            {
                throw new Exception("Failed");
            }
        }


        public void Stop()
        {
            try
            {
                _Client.Close();
                _Client = null;
            }
            catch { _Client = null; }
        }

        void socket_MessageReceived(object sender, WebSocket4Net.MessageReceivedEventArgs e)
        {
            try
            {
                var _data = e.Message.Split('|');
                switch (_data[0])
                {
                    case "Authurization":
                        Data = _data[1];
                        break;
                    case "Login":
                        Data = _data[1];
                        break;
                    case "Login_UserData":
                        Data = _data[1];
                        break;
                    case "Register":
                        Data = _data[1];
                        break;
                    case "GetInfoUser":
                        break;
                }
            }
            catch { }

        }
        void socket_DataReceived(object sender, WebSocket4Net.DataReceivedEventArgs e)
        {

        }
    }
}
